from rest_framework.response import Response
from rest_framework import status
from typing import Any

def _extract_error_message(err: Any) -> str:
    """
    从 serializer.errors 等可能的结构中递归提取第一个可用的错误消息字符串。
    支持 dict, list, tuple, str, Exception 等。
    如果无法提取，返回通用错误信息。
    """
    if err is None:
        return "Request Failed"

    # 已经是字符串
    if isinstance(err, str):
        return err

    # Exception
    if isinstance(err, Exception):
        return str(err)

    # 字典
    if isinstance(err, dict):
        for v in err.values():
            msg = _extract_error_message(v)
            if msg:
                return msg
        return "Request Failed"

    # 列表/元组
    if isinstance(err, (list, tuple)):
        for item in err:
            msg = _extract_error_message(item)
            if msg:
                return msg
        return "Request Failed"

    # 其他类型
    try:
        return str(err)
    except Exception:
        return "Request Failed"


def success_response(data=None, message="Request Success", code=200):
    """成功响应"""
    response_data = {
        'status': 'success',
        'code': code,
        'info': message,
        'data': data
    }
    return Response(response_data, status=status.HTTP_200_OK)


def error_response(message="Request Failed", code=400, data=None):
    """错误响应"""
    user_friendly_message = _extract_error_message(message)

    response_data = {
        'status': 'error',
        'code': code,
        'info': user_friendly_message,
        'data': data
    }

    # 根据错误代码选择HTTP状态码
    http_status = status.HTTP_400_BAD_REQUEST
    if code == 401:
        http_status = status.HTTP_401_UNAUTHORIZED
    elif code == 403:
        http_status = status.HTTP_403_FORBIDDEN
    elif code == 404:
        http_status = status.HTTP_404_NOT_FOUND
    elif code == 500:
        http_status = status.HTTP_500_INTERNAL_SERVER_ERROR

    return Response(response_data, status=http_status)
